var express = require("express");
var router = express.Router();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

/* 获取收藏数 */
router.get("/num", async (req, res) => {
  const { topic_id, topic_type } = req.query;

  const collect_num = await prisma.num_collect.findFirst({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
    },
  });

  res.json(collect_num == null ? 0 : collect_num.num);
});

/* 判断用户是否收藏 */
router.get("", async (req, res) => {
  const { topic_id, topic_type } = req.query;

  const collect = await prisma.user_collect.findMany({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
      user_id: req.auth.user.user_id,
    },
  });

  res.json(collect.length >= 1);
});

/* 切换用户收藏状态 */
router.post("/change", async (req, res) => {
  const { topic_id, topic_type } = req.body;

  //获取收藏状态
  const collect = await prisma.user_collect.findMany({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
      user_id: req.auth.user.user_id,
    },
  });

  //获取收藏数
  const collect_num = await prisma.num_collect.findFirst({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
    },
  });

  //用户取消收藏
  if (collect.length >= 1) {
    //删除用户收藏记录
    const collect_delete = await prisma.user_collect.deleteMany({
      where: {
        topic_id: topic_id,
        topic_type: parseInt(topic_type),
        user_id: req.auth.user.user_id,
      },
    });
    //收藏数-1
    const num_decre = await prisma.num_collect.updateMany({
      where: { topic_id: topic_id, topic_type: parseInt(topic_type) },
      data: {
        num: {
          decrement: 1,
        },
      },
    });
    res.json(collect_num == null ? 0 : collect_num.num - 1);
  }
  //用户收藏
  else {
    //新增用户收藏记录
    const new_collect = await prisma.user_collect.create({
      data: { topic_id: topic_id, topic_type: parseInt(topic_type), user_id: req.auth.user.user_id },
    });
    if (collect_num == null) {
      const new_collect_num = await prisma.num_collect.create({
        data: { topic_id: topic_id, topic_type: parseInt(topic_type), num: 1 },
      });
    } else {
      const num_incre = await prisma.num_collect.updateMany({
        where: { topic_id: topic_id, topic_type: parseInt(topic_type) },
        data: {
          num: {
            increment: 1,
          },
        },
      });
    }
    //返回收藏数
    res.json(collect_num == null ? 1 : collect_num.num + 1);
  }
});

//查询用户收藏id列表
//topic_type:主题类型; 0: 景区, 1: 文章
router.post("/get", async (req, res) => {
  const { topic_type } = req.body;
  const collectId = await prisma.user_collect.findMany({
    where: {
      user_id: req.auth.user.user_id,
      topic_type: parseInt(topic_type),
    }
  });
  res.json(collectId);
});

module.exports = router;
